package com.cloud.xtools.user.controller.admin;

import com.cloud.xtools.common.controller.BaseController;
import com.cloud.xtools.common.response.ApiResponse;
import com.cloud.xtools.common.response.PageList;
import com.cloud.xtools.common.validator.annotation.EntityExist;
import com.cloud.xtools.user.domain.entity.Role;
import com.cloud.xtools.user.domain.query.admin.RoleQuery;
import com.cloud.xtools.user.domain.request.admin.RoleCreateRequest;
import com.cloud.xtools.user.domain.request.admin.RoleUpdateRequest;
import com.cloud.xtools.user.service.admin.RoleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Daixinguo
 */
@RestController
@RequestMapping("api/user/admin")
@RequiredArgsConstructor
@Validated
public class RoleController extends BaseController {
    private final RoleService roleService;

    @GetMapping("roles")
    public ApiResponse<PageList> list(@ModelAttribute RoleQuery roleQuery) {
        return success(roleService.list(roleQuery));
    }

    @PostMapping("roles")
    public ApiResponse<Object> add(@Valid @RequestBody RoleCreateRequest roleCreateRequest) {
        return created(roleService.add(roleCreateRequest));
    }

    @PutMapping("roles/{id}")
    public ApiResponse<Object> edit(@EntityExist(entity = Role.class) @PathVariable Long id, @Valid @RequestBody RoleUpdateRequest roleUpdateRequest) {
        roleService.edit(id, roleUpdateRequest);
        return success("更新成功");
    }

    @DeleteMapping("roles/{id}")
    public ApiResponse<Object> remove(@EntityExist(entity = Role.class) @PathVariable Long id) {
        roleService.destroy(id);
        return noContent();
    }

    @PostMapping("roles/{id}/assign-permission")
    public ApiResponse<Object> assignPermission(@EntityExist(entity = Role.class) @PathVariable Long id, @RequestBody Map<String, List<Long>> requestBody) {
        roleService.assignPermission(id, requestBody.get("permission_ids"));
        return success("分配成功");
    }
}
